package com.zw.cloud.utils;

import cn.hutool.json.JSONUtil;
import com.dingtalk.api.DefaultDingTalkClient;
import com.dingtalk.api.DingTalkClient;
import com.dingtalk.api.request.OapiRobotSendRequest;
import com.dingtalk.api.response.OapiRobotSendResponse;
import com.taobao.api.ApiException;
import lombok.extern.slf4j.Slf4j;
import org.apache.tomcat.util.codec.binary.Base64;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.Objects;
import java.util.concurrent.CompletableFuture;


/**
 * https://open.dingtalk.com/document/orgapp/custom-bot-to-send-group-chat-messages
 * 加签
 * https://open.dingtalk.com/document/robots/customize-robot-security-settings
 */
@Slf4j
public class DingTalkUtils {

    private static String br = " \n\n ";


    public static void sendDingTalkMsgWithSign(String title,String tid,String uri,Throwable e) {
        CompletableFuture.runAsync(() -> {
            String msg = "#### 程序运行出错\n" +
                    "> uri : "+ uri + br +
                    "> tid : "+ tid + br +
                    "> error : "+ e + br;
            try {
                sendDingTalkMsgWithSign(title,"3a93469afdb2c38e22f0944e7f61a9b4d2e95a0138901d813ce6fe2c33dd1145","SECd51ae59f656260a2f859e4e149a54e120c8673a9aa789cf60f7ee20f09048a49",msg);
            } catch (ApiException ex) {
                log.error("[DingTalkUtils][sendDingTalkMsgWithSign] error is ", e);
            }
        });
    }


    private static void sendDingTalkMsgWithSign(String title,String token,String sign,String msg) throws ApiException {
        long timestamp = System.currentTimeMillis();
        String genSign;
        try {
            genSign = genSign(timestamp, sign);
        } catch (NoSuchAlgorithmException | UnsupportedEncodingException | InvalidKeyException e) {
            log.error("[DingTalkUtils][sendDingTalkMsgWithSign] token is {}, sign is {},error is ", token,sign,e);
            return;
        }
        DingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/robot/send?access_token=" + token + "&timestamp=" + timestamp + "&sign=" + genSign);
        OapiRobotSendRequest request = new OapiRobotSendRequest();
        request.setMsgtype("markdown");
        OapiRobotSendRequest.Markdown markdown = new OapiRobotSendRequest.Markdown();
        markdown.setTitle(title);
        // <font color=#0000FF>蓝色字体</font>
        markdown.setText(msg);
        request.setMarkdown(markdown);

        OapiRobotSendRequest.At at = new OapiRobotSendRequest.At();
        at.setIsAtAll(true);
        request.setAt(at);
        OapiRobotSendResponse execute = client.execute(request);
        if (!execute.isSuccess()) {
            log.error("[DingTalkUtils][sendDingTalkMsgWithSign] error, request is {}, execute is {}", JSONUtil.toJsonStr(request),JSONUtil.toJsonStr(execute));
        }
    }

    private static String genSign(long timestamp,String secret) throws NoSuchAlgorithmException, UnsupportedEncodingException, InvalidKeyException {
        String stringToSign = timestamp + "\n" + secret;
        Mac mac = Mac.getInstance("HmacSHA256");
        mac.init(new SecretKeySpec(secret.getBytes(StandardCharsets.UTF_8), "HmacSHA256"));
        byte[] signData = mac.doFinal(stringToSign.getBytes(StandardCharsets.UTF_8));
        return URLEncoder.encode(new String(Base64.encodeBase64(signData)),"UTF-8");
    }
}
